<?php
namespace Api\Controller;

use Api\Model\OrderModel;
use Com\Message;

class OrderController extends ApiController
{
    /*
     * 生成订单号
     *
     */
    function build_order_no()
    {
        /* 选择一个随机的方案 */
        mt_srand((double) microtime() * 1000000);
        
        return date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
    }


    //--提交订单
    public function submitOrder()
    {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        
        $Order = D('order');
        
        $data = I('post.');

        if (!isset($data['cids']) || empty($data['cids'])) {
            response(-1, null, '购物车项不能为空');
        }

        $cids = $data['cids'];
        is_array($cids) || $cids = str2arr($cids, ',');
        $carts = M('cart')->where(array('uid'=>API_UID, 'id'=>array('in',$cids)))->select();
        $carts || response(-1, null, '购物车项参数有误');
        if (!isset($data['receiver_id']) || empty($data['receiver_id'])) {
            response(-1, null, '收货地址不能为空');
        }


        $receiver = M('member_receive')->find($data['receiver_id']);
        $receiver || response(-1, null, '收货地址参数有误');
        $res = $Order->createOrder($carts, $receiver);
        $res !== false ? response(1, $res) : response(-2, null, $Order->getError());
    }

    /**
     * 获取支付订单所需播豆和余额
     */
    public  function getorderscore(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $uid=API_UID;
        params_exist(array('order_no'));
        $order_no=I('order_no');

        $cash_rate = M('config_private','cmf_')->getField('cash_rate');
        //合并订单支付
        if(substr($order_no,0,3)=='MG_'){
            $order = D('merge_order')->where('order_no="' . $order_no . '"')->find();
            if ($cash_rate) {
                $order_price = $order['price'] * $cash_rate;
            }
        }else {
            $order = M('order')->where('order_no='.I('order_no'))->find();
            if ($cash_rate) {
                $order_price = $order['price'] * $cash_rate;
            }
        }

        $username = M('ucenter_member')->where('id=' . $uid)->getField('username');
            //$mycoin = M('users', 'cmf_')->where('user_login=' . $username)->getField('coin');
        $data['order_price'] = $order_price;
        //$data['mycoin'] = number_format($mycoin,2);
        response(1, $data);
    }




    /**
     * 余额支付 订单
     */
    public function balancePayOrder(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $uid = API_UID;
        //商品
        params_exist(
            array(
                'order_no'
            )
        );
        $order_no= I('post.order_no');
        $order = D('order')->where('order_no='.$order_no)->find();
        if($order['pay_status']==1){
            response(-1,'','您已经支付过了');
        }
        $use_price = $order['price'];//取整

        $money =M('member')->where('uid='.$uid)->getField('amount');

        if($use_price>$money){
            response(-1,'','您的账户余额不足，请选择其他支付方式');
        }

        //合并订单支付
        if(substr($order_no,0,3)=='MG_'){

            $order = D('merge_order')->where('order_no="' . $order_no . '"')->find();
            if($order['price']>$money){
                response(-1,'','您的账户余额不足，请选择其他支付方式');
            }
            if($order){
                $order_ids = explode(',',$order['order_ids']);
                foreach ($order_ids as $order_id){
                    M('order')->where('id="'.$order_id.'"')->Save(array(
                        'status'     => 1,
                        'pay_status' => 1,
                        'pay_time'   => time(),
                        'pay_style' => 40
                    ));
                    $order = M('order')->where('id='.$order_id)->find();
                    //消费记录
                    payrecord($uid,$order_id,$order['price'],3,0);

                    //余额支付订单
                    M('member')->where('uid=' . $uid)->setDec('amount', $order['price']);
                    //余额提示
                    $tmobile=M('ucenter_member')->where('id='.$uid)->getField('username');
                    $tflag= M('prompt','cmf_')->where('mobile='.$tmobile)->find();
                    if($tflag){
                        M('prompt','cmf_')->where('mobile='.$tmobile)->setInc('wallet',1);
                    }else{
                        $tdata['wallet'] =1;
                        $tdata['uptime'] =time();
                        M('prompt','cmf_')->where('mobile='.$tmobile)->add($tdata);
                    }

                    //余额提示
                    $mobile=M('ucenter_member')->where('id='.$uid)->getField('username');
                    $tflag= M('prompt','cmf_')->where('mobile='.$mobile)->find();
                    if($tflag){
                        M('prompt','cmf_')->where('mobile='.$mobile)->setInc('wallet',1);
                    }else{
                        $tdata['wallet'] =1;
                        $tdata['uptime'] =time();
                        M('prompt','cmf_')->where('mobile='.$mobile)->add($tdata);
                    }

                    M('order_product')->where(array('order_id' => $order_id))->save(array('create_time' => time(), 'update_time' => time()));

                    $productid_result = M('order_product')->field('product_id')->where(array('order_id' => $order_id))->find();
                    $userid_result = M('product')->field('uid')->where(array('id' => $productid_result['product_id']))->find();
                    $phone_result = M('ucenter_member')->field('username')->where(array('id' => $userid_result['uid']))->find();
                    $sales = M('product')->where(array('id' => $productid_result['product_id']))->getField('sales');
                    M('product')->where(array('id' => $productid_result['product_id']))->save(array('sales' => intval($sales) + 1));
                    Message::send($phone_result['username'],'#code#='.$order['order_no'],'50603');
                }
            }
        }else {
            $order = D('order')->where('order_no='.$order_no)->find();
            $order || response(-1,'订单不存在！');
            D('order')->where('id='. $order['id'])->Save(
                array(
                    'pay_status' => OrderModel::ORDER_PAY,
                    'pay_time' => time(),
                    'order_status' => 1,
                    'status' => 1,
                    'pay_status' => 1,
                    'pay_time' => time(),
                    //'score_num' => $use_price,
                    'pay_style' => 40,//order_style 支付方式 10 积分，20 支付宝，30 微信 40 余额支付
                )
            );

            //消费记录
            payrecord($uid,$order['id'],$order['price'],3,0);

            //余额支付订单
            M('member')->where('uid=' . API_UID)->setDec('amount', $use_price);
            //余额提示
            $mobile=M('ucenter_member')->where('id='.API_UID)->getField('username');
            $tflag= M('prompt','cmf_')->where('mobile='.$mobile)->find();
            if($tflag){
                M('prompt','cmf_')->where('mobile='.$mobile)->setInc('wallet',1);
            }else{
                $tdata['wallet'] =1;
                $tdata['uptime'] =time();
                M('prompt','cmf_')->where('mobile='.$mobile)->add($tdata);
            }

            /**
             * 短信提示
             */

            $productid_result = M('order_product')->field('product_id')->where(array('order_id' => $order['id']))->find();

            M('order_product')->where(array('order_id' => $order['id']))->save(array('create_time' => time(), 'update_time' => time()));

            if (!empty($productid_result)) {
                $userid_result = M('product')->field('uid')->where(array('id' => $productid_result['product_id']))->find();
                if (!empty($userid_result)) {
                    $phone_result = M('ucenter_member')->field('username')->where(array('id' => $userid_result['uid']))->find();
                    $sales = M('product')->where(array('id' => $productid_result['product_id']))->getField('sales');
                    M('product')->where(array('id' => $productid_result['product_id']))->save(array('sales' => intval($sales) + 1));
                    Message::send($phone_result['username'], '#code#=' . $order['order_no'], '50603');
                }
            }
        }
        response(1,array('id'=>$order_id,'order_no'=>$order['order_no']),'支付成功！');
    }


    /**
     * 购买播豆商品
     */
    public function buyScoreProduct(){

        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        //商品
        params_exist(
            array(
                'receiver_id','id'
            )
        );
        $id = I('post.id');     //商品ID
        $receiver_id = I('post.receiver_id');       //收货地址
        $quantity = 1;             //购买数量
        unset($_POST['id']);
        unset($_POST['receiver_id']);
        $M_product = D('product');
        $product = $M_product -> where('id='.$id)->find();
        $product || response(-1,'商品不存在！');
        if($product['type']=='score'){
            $use_score = $product['use_score']*$quantity;
        }else{
            response(-1,'此商品不是积分商品！');
        }
        $user_score = D('member')->where('uid='.API_UID)->getField('score');
        $use_score<$user_score || response(-1,'您的账户不足'.$use_score.'积分！');
        $receiver = M('member_receive')->find($receiver_id);
        $receiver || response(-1, null, '收货地址参数有误');
        $carts = array(
            array(
                'product_id'=> $id,
                'quantity'=>$quantity
            )
        );

        $res = D('order')->createScoreOrder($carts, $receiver,true);
        if($res){
            $res = $res[0];
            $order_no = $res['order_no'];
            D('member')->where('uid='.API_UID)->setDec('score',$use_score);
            //--修改订单状态
            D('order')->where('order_no="'.$order_no.'"')->Save(array(
                'score_num' => $use_score,
                'order_status' => 1,
                'pay_time' => time()
            ));
            addMessage(3,'积分使用通知','您兑换了商品['.$product['title'].']使用了'.$use_score.'积分',API_UID,0);
            response(1,$res,'商品兑换成功');
        }else{
            response(-2, null, D('order')->getError());
        }
    }

    //--立即购买的确认订单
    public function quickSubmitOrder()
    {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);

        $Order = D('order');
        $uid = API_UID;
        $data = I('post.');

        if (!isset($data['product_id']) || empty($data['product_id'])) {
            response(-1, null, '商品ID不能为空');
        }

        $carts = array(
            array(
                'product_id' => $data['product_id'],
                'quantity' => $data['quantity'],
                'option_ids'=>$data['product_option_id']
            )
        );

        $product_info = M("product")->where(array('id'=>$data['product_id'],'status'=>1))->find();
        if($data['quantity']>$product_info['quantity']){
            response(-2, null, '商品库存不足');
        }

        if (!isset($data['receiver_id']) || empty($data['receiver_id'])) {
            response(-1, null, '收货地址不能为空');
        }


        $receiver = M('member_receive')->find($data['receiver_id']);
        $receiver || response(-1, null, '收货地址参数有误');
        $remarks=$data['remarks'];
        $res = $Order->createOrder($carts, $receiver,true,$uid,$remarks);
        $res !== false ? response(1,'','兑换成功!') : response(-2, null, $Order->getError());
    }

    //提交订单
    public function confirmOrder() {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $Order = D('order');
        $id = I('post.id', 0);
        $info = $Order->find($id);
        $info || response(-1, null, '参数有误');
        $info['uid'] == API_UID || response(-1, '', '无权操作此订单');
        if ($info['order_status'] != OrderModel::ORDER_UNCONFIRMED) {
            response(-1, null, '订单已提交，不要重复提交');
        }
        $Order->where(array('id'=>$id))->setField(array('order_status'=>OrderModel::ORDER_CONFIRMED,'confirm_time'=>NOW_TIME));
        response(1);
    }

    //--取消订单
    public function cancelOrder()
    {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $Order = D('order');
        $id = I('post.id', 0);
        $info = $Order->find($id);
        $info || response(-1, null, '参数有误');
        $info['uid'] == API_UID || response(-1, '', '无权操作此订单');
        if ($info['pay_status']!=0) {
            response(-1, null, '此不能取消订单');
        }
        $Order->where(array('id'=>$id))->setField(array('order_status'=>OrderModel::ORDER_CANNELED));
        $order_products = M('order_product')->where(array('order_id'=>$id))->select();
       /* foreach ($order_products as $order_product) {
            M('product')->where(array('id'=>$order_product['product_id']))->setInc('quantity', intval($order_product['quantity']));
        }*/
       //M()->getField();
        response(1);
    }

    //发货
    public function shippingOrder(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        
        $Order = D('order');
        $id = I('post.id', 0);
        
        $info = $Order->find($id);
        $info || response(-1, null, '参数有误');
        
        if ($info['order_status'] != OrderModel::ORDER_CONFIRMED) {
            response(-1, null, '订单未提交');
        }
        if ($info['shipping_status'] == OrderModel::SHIPPING_SHIPPED) {
            response(-1, null, '订单已发货，请不要重复发货');
        }
        
        $prefix = C('DB_PREFIX');
        $l_table = $prefix.('product');
        $r_table = $prefix.('order_product');
        $model = M()->table($l_table.' l')->join($r_table.' r ON l.id = r.product_id');
        $filters['r.order_id'] = $id;
        $filters['l.uid'] = API_UID;
        $order_products = $model->where($filters)->field(array('r.id'))->select();
        $order_products || response(-2, null, '不能操作此订单');
        foreach ($order_products as $order_product) {
            M('order_product')->where(array('id'=>$order_product['id']))->setField(array('shipping_status'=>1));
        }
        $ord_pro=M('order_product')->where('order_id='.$id)->select();
        foreach ($ord_pro as $ord){
            $quantity = $ord['quantity'];
            M('product')->where('id='.$ord['product_id'])->setDec('quantity',$quantity);
            M('product')->where('id='.$ord['product_id'])->setInc('sales',$quantity);
        }
        $count = M('order_product')->where(array('order_id'=>$id, 'shipping_status'=>0))->count() | 0;
        if ($count == 0) {
            $Order->where(array('id'=>$id))->setField(array('shipping_status'=>OrderModel::SHIPPING_SHIPPED, 'shipping_time'=>NOW_TIME));
        } else {
            $Order->where(array('id'=>$id))->setField(array('shipping_status'=>OrderModel::SHIPPING_PARTIALSHIPMENT, 'shipping_time'=>NOW_TIME));
        }
        response(1);
    }


    public function receiveOrder() {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $Order = D('order');
        $id = I('post.id', 0);
        $info = $Order->find($id);
        $info || response(-1, null, '参数有误');
        $info['uid'] == API_UID || response(-1, '', '无权操作此订单');
        if ($info['pay_status'] != OrderModel::ORDER_UNPAY && $info['shipping_status'] != OrderModel::SHIPPING_SHIPPED) {
            response(-1, null, '订单已提交，不能取消订单');
        }

        $Order->where(array('id'=>$id))->setField(array('order_status'=>OrderModel::ORDER_COMPLATED,'complate_time'=>NOW_TIME));
        response(1);
    }

    /**
     * 删除订单
     */
    public function deleteOrder() {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $Order = D('order');
        $id = I('post.id', 0);
        $info = $Order->find($id);
        $info || response(-1, null, '参数有误');
        $info['uid'] == API_UID || response(-1, '', '无权操作此订单');

     /*   if ($info['order_status'] != OrderModel::ORDER_CANNELED && $info['order_status'] != OrderModel::ORDER_COMPLATED) {
            response(-1, null, '订单尚未完成，不能删除订单');
        }*/

        $Order->where(array('id'=>$id))->delete();
        $order_products = M('order_product')->where(array('order_id'=>$id))->delete();
        response(1);
    }


    public function comments() {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $Order = D('order');
        $id = I('post.id', 0);
        $info = $Order->find($id);
        $info || response(-1, null, '参数有误');
        $list = M('product_comment')->where(array('order_id'=>$id))->order('id DESC')->select();
        foreach ($list as &$item) {
            $item['avatar'] = get_avatar($item['uid']);
            $username = get_username($item['uid']);
            $item['username'] = substr_replace($username, '****', - 4);
            $item['format_time'] = time_format($item['create_time'], "Y-m-d h:i:s");
            $images = array();
            $images_id = str2arr($item['cover_ids'], ',');
            foreach ($images_id as $cover_id) {
                $images[] = get_url($cover_id);
            }
            $item['images'] = $images;
            $item['messages'] = M('product_comment_message')->where(array('comment_id'=>$item['id']))->select();
        }
        response(1, $list);
    }

    /**
     * 获取我的订单
     * 
     * @param
     *            string token
     * @param
     *            int page
     * @param
     *            int page_size
     * @param
     *            int status
     */
    public function getMyOrders()
    {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $Order = D('order');
        $page = I('post.page', 1);
        $page_size = I('post.page_size', 10);
        $offset = ($page - 1) * $page_size;
        $status = I('post.status');
        
        $filters['uid'] = API_UID;
        switch ($status) {

            case '7':
                //--已申请退款
                $filters['pay_status'] = OrderModel::ORDER_APPLY_REFUND;
                break;
            case '8':
                //--已退款
                $filters['pay_status'] = OrderModel::ORDER_REFUND;
                break;
            case '0':
                //--未支付订单
                $filters['pay_status'] = OrderModel::ORDER_UNPAY;
                break;
            case '1':
                //--待发货
                $filters['order_status'] = OrderModel::ORDER_CONFIRMED;
                $filters['shipping_status'] = array('in', array(OrderModel::SHIPPING_UNSHIPPED, OrderModel::SHIPPING_PARTIALSHIPMENT));
                $filters['pay_status'] = OrderModel::ORDER_PAY;
                break;
            case '2':
                //--待收货
                $filters['order_status'] = OrderModel::ORDER_CONFIRMED;
                $filters['shipping_status'] = OrderModel::SHIPPING_SHIPPED;
                $filters['pay_status'] = OrderModel::ORDER_PAY;
                break;
            case '3':
                //--订单完成
                $filters['order_status'] = OrderModel::ORDER_COMPLATED;
                $filters['shipping_status'] = OrderModel::SHIPPING_SHIPPED;

                $filters['review_status'] = OrderModel::REVIEW_REVIEWED;
                break;
            case '4':
                //--待评论
                $filters['order_status'] = OrderModel::ORDER_COMPLATED;
                $filters['shipping_status'] = OrderModel::SHIPPING_SHIPPED;

                $filters['review_status'] = OrderModel::REVIEW_UNREVIEWED;
                break;
            case '5':
                //--取消订单
                $filters['order_status'] = OrderModel::ORDER_CANNELED;
                break;
            case '6':
                //--
                $filters['order_status'] = array('in', array(OrderModel::ORDER_COMPLATED, OrderModel::ORDER_CONFIRMED));
                break;
        }
        
        $total = $Order->where($filters)->count() | 0;
        $list = $Order->where($filters)->limit($offset, $page_size)->order('id DESC')->select();

        foreach ($list as &$item) {
            $item['status_text'] = $Order->getOrderStatusText($item); 
            $order_products = M('order_product')->where(array('order_id'=>$item['id']))->select();
            foreach ($order_products as &$order_product) {
                $product_info = M('product')->where(array('id'=>$order_product['product_id']))->find();
                $order_product['image_path'] = get_url(get_table_field($product_info['id'], 'product_id', 'cover_id', 'product_image'));
                if ($product_info['type'] == 'xianzhi') {
                //    $order_product['shop_title'] = '卖家' . get_username($product_info['uid']);
                } else {
                    $shop_info = M('shop')->where(array('id'=>$product_info['shop_id']))->find();
                  //  $order_product['shop_title'] = $shop_info['title'];
                }
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);;
                $order_product['price'] = format_money($order_product['price']);
            }

            $order=M('order')->where('id='.$item['id'])->find();
            $province_name= M('hat_province')->where('province_id='.$order['province_id'])->getField('province');
            $city_name = M('hat_city')->where('city_id='.$order['city_id'])->getField('city');
            $area_name = M('hat_area')->where('area_id='.$order['area_id'])->getField('area');
            $area=$province_name.$city_name.$area_name.$item['address'];
            $item['area']=$area;
            $item['products'] = $order_products;
            $item['price'] = format_money($item['price']);
        }
        
        $result = array();
        $result['result'] = $list?$list:array();
        $result['total'] = $total;
        $list !== false ? response(1, $result) : response(-2);
    }

    /**
     * 合并订单
     */
    public function merge_order(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);

        params_exist(array(
            'order_ids'
        ));

        $order_ids = explode(',',I('post.order_ids'));
        $order_ids_arr = array();
        $order_arr = array();
        $merge_order = D('merge_order');
        $order = D('order');
        $order_price = 0.00;
        $order_ids1 = array();
        $order_name = '';
        foreach ($order_ids as $order_id){
            if($order_id){
                $order_det = $order->where('id='.$order_id)->find();
                if($order_det){
                    if(!$order_name) {
                        $order_name = D ( 'order_product' )->where('order_id='.$order_id)->getField ('product_title');
                        $order_name .= '等商品';
                    }
                    $order_ids1[]=$order_id;
                    $order_price += $order_det['price'];
                }else{
                    response(-1, '订单ID:'.$order_id.'不存在!');
                }
            }
        }
        $order_no = 'MG_'.date('YmdHis').rand(1000000,9999999);
        $data = array(
            'order_no' => $order_no,
            'price'    => $order_price,
            'name'     => $order_name,
            'order_ids'=> implode(',',$order_ids1),
            'time'     => time(),
            'pay_status'=> 0,
        );
        $res = $merge_order->add($data);
        if($res){
            response(1,$data);
        }else{
            response(-1,'出现错误，请稍后再试！');
        }


    }
    /**
     * 获取订单详情
     * 
     * @param
     *            int order_id
     */
    public function getOrderDetail()
    {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $Order = D('order');
        $id = I('post.id', 0);
        $info = $Order->find($id);
        $info || response(-1, null, '参数有误');
        //--为了商家也可以获取订单详情
        $info['status_text'] = $Order->getOrderStatusText($info);
        $order_products = M('order_product')->where(array('order_id'=>$id))->select();
        foreach ($order_products as &$order_product) {
            $product_info = M('product')->find($order_product['product_id']);
            $order_product['image_path'] = get_url(get_table_field($product_info['id'], 'product_id', 'cover_id', 'product_image'));
            if ($product_info['type'] == 'xianzhi') {
                $order_product['shop_title'] = '卖家' . get_username($product_info['uid']);
            } else {
                $shop_info = M('shop')->find($product_info['shop_id']);
                $order_product['shop_title'] = $shop_info['title'];
            }



            if ($product_info['in_special_panic']) {
                $product_panic_info = M('product_special_panic')->where(array('product_id'=>$product_info['product_id']))->find();
                $special_panic_info = M('special_panic')->where(array('id'=>$product_panic_info['special_panic_id'], 'status'=>1))->find();

                if ($special_panic_info) {
                    $special_panic_result_starttime=strtotime(date('Y-m-d')." ".date('H:i:s',$special_panic_info['start_time']));
                    $special_panic_result_endtime=strtotime(date('Y-m-d')." ".date('H:i:s',$special_panic_info['end_time']));
                    if(($special_panic_result_starttime<=NOW_TIME) && ($special_panic_result_endtime>= NOW_TIME)){
                        $total_price = $order_product['price'] *  $order_product['quantity'];
                        if ($total_price >= $product_panic_info['condition_price']) {
                            $order_products[]['price'] =  $order_product['price'] * $product_panic_info['discount'] * 0.1;

                        }
                    }
                }
            }

        }
        $info['products'] = $order_products;
        response(1, $info);
    }

    //======申请退款
    public function apply_refund(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        params_exist(array(
            'order_id','refund_desc'
        ));
        $order_id = I('post.order_id');
        $order = M('order')->Where('id="'.$order_id.'"')->find();
        if ($order){
            $shop_id = M('order_product')->where('order_id='.$order_id)->getField('shop_id');
            !$order['is_score_product'] || response(-1,'平台积分商品不允许退款');
            $shop_id || response(-1,'平台商品不允许退款');
//            echo API_UID;EXIT;
            $order['uid'] == API_UID || response(-1, '', '无权操作此订单');
            if($order['order_status']!=1){
                response(-1,'此订单不能退款！');
            }
            if($order['pay_status']==0){
                response(-1,'订单还未支付！');
            }
            if($order['pay_status']==OrderModel::ORDER_APPLY_REFUND){
                response(-1,'您已经申请过退款了！');
            }
            if($order['pay_status']==0){
                response(-1,'此订单未支付！');
            }
            $res = M('order')->Where('id="'.$order_id.'"')->Save(array(
                'pay_status' => OrderModel::ORDER_APPLY_REFUND,
                'refund_desc' => I('post.refund_desc'),
            ));
            if($res){
                response(1,'申请退款成功，请耐心等待！');
            }else{
                response(-1,'系统出现错误！');
            }
        }else{
            response(-1,'您要退款的订单并不存在！');
        }
    }

    /**
     * 确认收货
     * 
     * @param
     * int order_id
     */
    public function confirmProduct()
    {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        params_exist(array(
            'order_id'
        ));


        $id = I('post.order_id');
        $M_order = D('order');
        $orderinfo = $M_order->where(array('id'=>$id))->find();
        empty($orderinfo) && response(- 2, '', '订单不存在');
        if($orderinfo['order_status']==OrderModel::ORDER_COMPLATED){
            response(-1,'订单已确认');
        }
        $map = array(
            'id' => $id
        );

        $M_order->where($map)->setfield('status', 5);
        $product_id=M('Order_product')->where('order_id='.$id)->getField('product_id');
        $product_result=M('product')->where('id='.$product_id)->find();
        //判断是否为抢购会商品 in_special_panic =1
        //判断支付方式是否为积分支付 pay_style =10 //20 支付宝，30 微信


        $product_special_panic=M('product_special_panic')->where('product_id='.$product_id)->find();
        $special_panic_id=$product_special_panic['special_panic_id'];
        $special_panic_result=M('special_panic')->where('id='.$special_panic_id)->find();


        $special_panic_result_starttime=strtotime(date('Y-m-d')." ".date('H:i:s',$special_panic_result['start_time']));
        $special_panic_result_endtime=strtotime(date('Y-m-d')." ".date('H:i:s',$special_panic_result['end_time']));

        if(($product_result['in_special_panic']==1 && $special_panic_result_starttime <=NOW_TIME && $special_panic_result_endtime>= NOW_TIME) || $orderinfo['pay_style']==10){//为抢购会商品或者积分支付商品，直接增加商家的回收积分即可。
            $products = D('order_product')->where('order_id='.$id)->select();
            foreach ($products as $k=>$product) {
                M('shop')->where('id=' . $product['shop_id'])->setInc ( 'recover_score', $orderinfo[ 'score_num' ] );
            }
        }else{
            //--将赠送积分转给购买者
            $M_order->giveScore($id);
            $shop_id = D('order_product')->where('order_id='.$id)->getField('shop_id');
            //增加商家的回收积分
            M ( 'shop' )->where ( 'id=' . $shop_id )->setInc ( 'recover_score', $orderinfo[ 'score_num' ] );
        }
        D('order')->where(array('id'=>$id))->setField(array('order_status'=>OrderModel::ORDER_COMPLATED,'complate_time'=>NOW_TIME));
        //增加商家余额
        $price = $orderinfo['price'];
        //平台抽成
        $info = M('shoprate')->find();
        $price = $price-$price*$info['rate']/100;
        $shop_uid  = M('shop')->where('id='.$orderinfo['shop_id'])->getField('uid');
        M('Member')->where('uid='.$shop_uid)->setInc('amount',$price);
        //商家消费记录
        payrecord($shop_uid,$id,$price,4,0);
        response(1);
    }

    /**
     * 定时修改订单状态
     */
    public function autoTake($uid){
        $uid = $_POST['uid'] ? $_POST['uid'] : $uid;
        $map['pay_status'] = 1;
        $map['uid'] = $uid;
        $M_order = D('order');
        $order = $M_order->where($map)->select();
        if($order) {
            foreach ($order as $key=>$val) {
                //发货后12后  自动更改订单状态为后台(已完成)    手机(待评价)
               if($val['create_time'] + 86400*12 > time()) {
                   $where['uid'] = $uid;
                   $where['pay_status'] = 1;
                    $data = $M_order->where($where)->save([
                        'order_status' =>2,
                        'shipping_status' =>2,
                        'pay_status' => 6,
                        'complate_time' => NOW_TIME
                    ]);
               }
                //手机端为(待评价10天后) 修改手机端显示状态 为交易完成
                if($val['create_time'] + 86400*22 > time()) {
                    $where['uid'] = $uid;
                    $where['pay_status'] = 6;
                    $data = $M_order->where($where)->save([
                        'review_status' =>1,
                        'complate_time' => NOW_TIME
                    ]);
                    //查询订单相关商品信息
                    $order_product = D('order_product')->where('order_id='.$val['id'])->find();
                    $comment = M('product_comment');
                    //添加好评
                    $data = array(
                        'order_id' => $val['id'],
                        'product_id' =>$order_product['product_id'],
                        'create_time' => NOW_TIME,
                        'uid' => $uid,
                        'content' => '',
                        'cover_ids' => '',
                        'rating_desc' => 5,
                        'rating_attitude' => 5,
                        'rating_speed' => 5,
                        'rating_shipping'=>5,
                        'rate' => 1
                    );

                    $add_comment = $comment->add($data);

                }

            $id = $val['id'];

            $map = array(
                'id' => $id
            );


           if($order_product['in_special_panic'] != 1){
                   //--将赠送积分转给购买者
                   $M_order->giveScore($id);
           }
            //增加商家的回收积分
            M ( 'shop' )->where ( 'id=' . $order_product['shop_id'] )->setInc ( 'recover_score', $order[ 'score_num' ] );

            //增加商家赠送积分

            D('order')->where(array('id'=>$id))->setField(array('order_status'=>OrderModel::ORDER_COMPLATED,'complate_time'=>NOW_TIME));
            response(1);
            }
        }
    }

    /**
     * 退货申请
     * 
     * @param
     *            int type 退款类型
     * @param
     *            int order_id 订单id
     * @param
     *            int product_id 退款产品
     * @param
     *            double money 退款金额
     * @param
     *            stirng reason
     * @param
     *            string explain 退款说明
     */
    public function applyforReturn()
    {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $M_order = M('order');
        $M_order_produdt = M('order_product');
        $M_product_return = M('product_return');
        
        // type 1 退款 2退货
        params_exist(array(
            'type',
            'order_id',
            'product_id',
            'money',
            'reason'
        ));
        
        $data = params_post(array(
            'type',
            'order_id',
            'product_id',
            'money',
            'reason',
            'explain'
        ));
        $cover_ids = I('post.cover_ids');
        is_array($cover_ids) && $cover_ids = implode(',', $cover_ids);
        
        // 订单信息
        $order_info = $M_order->where(array(
            'id' => $data['order_id'],
            'uid' => API_UID
        ))->find();
        empty($order_info) && response(- 2, '', '订单不存在');
        // 商品信息
        $produdt_info = $M_order_produdt->where(array(
            'product_id' => $data['product_id'],
            'order_id' => $data['order_id']
        ))->find();
        empty($produdt_info) && response(- 2, '', '订单不存在商品');
        
        // 退款条件
        if ((int) $order_info['status'] <= 0 || (int) $order_info['status'] > 6) {
            response(- 1, '', '此订单不符合退款条件');
        }
        
        ! preg_match("/^1|2$/", $data['type']) && response(- 1, '', '退款方式错误');
        ! preg_match("/^[0-9]+(.[0-9]{2})?$/", $data['money']) && response(- 1, '', '退金额错误格式错误');
        ! preg_match("/^.{0,200}$/", $data['reason']) && response(- 1, '', '退款原因200字以内');
        ! preg_match("/^.{0,250}$/", $data['explain']) && response(- 1, '', '退说明250字以内');
        
        (int) ($data['money']) > (int) ($produdt_info['price']) && response(- 1, '', '退款金额不能大于订单金额');
        $data['create_time'] = NOW_TIME;
        $data['uid'] = API_UID;
        $data['status'] = 1;
        $data['cover_ids'] = $cover_ids;
        
        // 检查退货表
        $M_product_return->where(array(
            'status' => 2,
            'product_id' => $data['product_id'],
            'order_id' => $data['order_id']
        ))->find() && response(- 1, '', '退款已完成');
        
        $M_product_return->where(array(
            'status' => 1,
            'product_id' => $data['product_id'],
            'order_id' => $data['order_id']
        ))->find() && response(- 1, '', '退款申请已提交,请等待商家退款');
        
        // 检查订单表是否已经退货
        $map_order_product = array(
            'product_id' => $data['product_id'],
            'order_id' => $data['order_id']
        );
        $map_order_product['return_status'] = array(
            'BETWEEN',
            "1,2"
        );
        
        $M_order_produdt->where($map_order_product)->find() && response(- 1, '', '退款申请冲突，请联系管理员');
        
        $apply_result = $M_product_return->add($data);
        
        if ($apply_result) {
            $M_order_produdt->where(array(
                'product_id' => $data['product_id'],
                'order_id' => $data['order_id']
            ))->setfield('return_status', 1);
            $M_order->where(array(
                'id' => $data['order_id']
            ))->setfield('status', 6);
        }
        $apply_result ? response(1) : response(- 9);
    }
    
}
?>